package 抢红包算法;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RobRedPacket {

    // 发红包算法，金额参数以分为单位

    public static List<Integer> divideRedPacket(Integer totalAmount, Integer totalPeopleNum) {
        List<Integer> amountList = new ArrayList<>();
        // 剩余金额
        Integer restAmount = totalAmount;
        // 剩余没抢的人数
        Integer restPeopleNum = totalPeopleNum;
        Random random = new Random();
        for (int i = 0; i < totalPeopleNum - 1; i++) {
            // 随机范围：[1，剩余人均金额的两倍)，左闭右开
            int amount = random.nextInt(restAmount / restPeopleNum * 2 - 1) + 1;
            // 扣钱
            restAmount -= amount;
            // 修改人数
            restPeopleNum--;
            // 得到此次抢到的金额
            amountList.add(amount);
        }
        // 缺陷：最后一个人拿到的红包不是均分的
        amountList.add(restAmount);
        return amountList;
    }

    public static void main(String[] args) {
        List<Integer> amountList = divideRedPacket(5000, 30);
        for (Integer amount : amountList) {
            System.out.println("抢到金额：" +
                    new BigDecimal(amount).divide(new BigDecimal(100)));
        }
    }
}
